package com.xy.util;

import android.content.Context;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;

import java.util.Locale;

/**
 * Created by XuYang
 * 2023/9/22
 * Email:544066591@qq.com
 */
public class TextToSpeechManager {

    private static TextToSpeechManager mInstance;
    private TextToSpeech tts;
    public static String mPackageName = "com.iflytek.speechcloud";

    public TextToSpeechManager() {
    }

    public static TextToSpeechManager getInstance() {
        if (mInstance == null) {
            Class var0 = TextToSpeechManager.class;
            synchronized (TextToSpeechManager.class) {
                if (mInstance == null) {
                    mInstance = new TextToSpeechManager();
                }
            }
        }

        return mInstance;
    }

    public void init(Context context) {
        this.tts = new TextToSpeech(context, (status) -> {
            if (status == 0 && this.tts != null) {
                this.tts.setEngineByPackageName(mPackageName);
                this.tts.setLanguage(Locale.CHINESE);
            }

        });
    }

    public void speak(CharSequence text) {
        if (null != this.tts) {
            this.stop();
            this.tts.speak(text, 0, (Bundle) null, (String) null);
        }

    }

    public void speak(CharSequence text, int mode) {
        if (null != this.tts) {
            this.stop();
            this.tts.speak(text, mode, (Bundle) null, (String) null);
        }

    }

    public void stop() {
        if (this.tts != null && this.tts.isSpeaking()) {
            this.tts.stop();
        }

    }

    public void release() {
        if (this.tts != null) {
            this.tts.stop();
            this.tts.shutdown();
            this.tts = null;
        }

    }
}
